﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SO.MyMoney.BookingWebPart
{
    [ToolboxItem(false)]
    public partial class BookingWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        private void ChangeAccountTypeImage()
        {
            try
            {
                if (AccountDropDown.SelectedItem != null)
                {
                    string accType = Globals.GetAccountType(int.Parse(AccountDropDown.SelectedItem.Value));

                    if (accType.ToUpper() == Definitions.FIELD_ACCOUNT_VALUE_CREDIT.ToUpper())
                    {
                        debPic.ImageUrl = "/MyMoneyGraphics/credit.png";
                    }
                    else
                    {
                        debPic.ImageUrl = "/MyMoneyGraphics/debit.png";
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error changing account type image", ex);
            }
        }

        private void LoadAccounts()
        {
            try
            {
                SPList list = SPContext.Current.Web.Lists.TryGetList(Definitions.BOOKING_ACCOUNT_LIST);
                if (list != null)
                {
                    foreach (SPListItem item in list.Items)
                    {
                        AccountDropDown.Items.Add(new ListItem(string.Format("{1} | {0}", item["Title"], item[Definitions.FIELD_ACCOUNT_NO]),
                            item.ID.ToString()));
                    }
                }

                ChangeAccountTypeImage();
            }
            catch (Exception ex)
            {
                
            }
        }

        private bool ValidateFields()
        {
            try
            {
                ErrorLabel.Text = string.Empty;

                DateTime temp = DateTime.Now;
                if (!DateTime.TryParse(BookingDate.Text, out temp))
                {
                    ErrorLabel.Text += "Please enter a valid booking date<br />";
                }

                if (BookingText.Text.Trim() == string.Empty)
                {
                    ErrorLabel.Text += "Please enter a booking text<br/>";
                }

                double tempdbl = 0;
                if (!double.TryParse(AmountText.Text, out tempdbl))
                {
                    ErrorLabel.Text += "Please enter a valid amount<br />";
                }

                return (ErrorLabel.Text == string.Empty);
            }
            catch (Exception ex)
            {
                throw new Exception("Error validating fields", ex);
            }
        }

        private void LoadMandatories()
        {
            try
            {
                SPList list = SPContext.Current.Web.Lists.TryGetList(Definitions.BOOKING_MANDATORY_LIST);
                if (list != null)
                {
                    foreach (SPListItem item in list.Items)
                    {
                        MandatoryDropDown.Items.Add(new ListItem(string.Format("{0}", item["Title"], item[Definitions.FIELD_MANDATORY_NUMBER]),
                            item.ID.ToString()));
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error loading mandatories list", ex);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            bool bookingOk = false;

            if (!Page.IsPostBack)
            {
                BookingDate.Text = DateTime.Now.ToShortDateString();
                LoadAccounts();

                if (Globals.IsMultiTenant)
                {
                    MandatoryPanel.Visible = true;
                    LoadMandatories();                    
                }
                else
                {
                    MandatoryPanel.Visible = false;                    
                }
            }

            if (Globals.IsMultiTenant)
            {
                bookingOk = Globals.MandatoryHasCurrentPeriod(int.Parse(MandatoryDropDown.SelectedItem.Value));
            }
            else
            {
                bookingOk = Globals.MandatoryHasCurrentPeriod(int.Parse(Globals.GetSettingValue(Definitions.SETTING_SYS_MANDATORY)));
            }
                        
            BookingDate.Enabled = bookingOk;
            BookingText.Enabled = bookingOk;
            AccountDropDown.Enabled = bookingOk;
            AmountText.Enabled = bookingOk;
            ExecuteBooking.Enabled = bookingOk;

            if (bookingOk)
            {
                ErrorLabel.Text = string.Empty;
            }
            else
            {
                ErrorLabel.Text = "No current booking period present";
            }
        }

        protected void ExecuteBooking_Click(object sender, EventArgs e)
        {
            try
            {
                if (ValidateFields())
                {
                    SPList list = SPContext.Current.Web.Lists.TryGetList(Definitions.BOOKING_LIST);
                    if (list != null)
                    {
                        int currentPeriod = int.Parse(Globals.GetSettingValue(Definitions.SETTING_CURR_PERIOD));

                        SPListItem item = list.Items.Add();
                        item["Title"] = BookingText.Text;
                        item[Definitions.FIELD_BOOKING_DATE] = DateTime.Parse(BookingDate.Text);
                        item[Definitions.FIELD_BOOKING_ACCOUNT] = int.Parse(AccountDropDown.SelectedItem.Value);
                        string accType = Globals.GetAccountType(int.Parse(AccountDropDown.SelectedItem.Value));
                        if (accType != string.Empty)
                        {
                            double amount = double.Parse(AmountText.Text);
                            if (accType.ToUpper() == Definitions.FIELD_ACCOUNT_VALUE_CREDIT.ToUpper())
                            {
                                amount = amount * (-1);
                            }

                            item[Definitions.FIELD_BOOKING_AMOUNT] = amount;
                        }
                        else
                        {
                            throw new Exception("Unknown account type");
                        }

                        int mandatoryId = 0;
                        if (Globals.IsMultiTenant)
                        {
                            mandatoryId = int.Parse(MandatoryDropDown.SelectedItem.Value);
                        }
                        else
                        {
                            mandatoryId = int.Parse(Globals.GetSettingValue(Definitions.SETTING_SYS_MANDATORY));
                        }

                        item[Definitions.FIELD_BOOKING_MANDATORY] = mandatoryId;
                        item[Definitions.FIELD_BOOKING_PERIOD] = Globals.GetCurrentPeriodByMandatory(mandatoryId);

                        item.Update();

                        BookingText.Text = string.Empty;
                        AmountText.Text = string.Empty;

                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Error while saving data";
            }
        }

        private void AccountDropDown_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ChangeAccountTypeImage();
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = ex.Message.ToString();
            }
        }
    }
}
